import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useWorkoutStore = defineStore('workout', () => {
  // 状态
  const currentWorkout = ref(null);
  const workoutHistory = ref([]);
  const workoutStats = ref({ weekly: 0, monthly: 0, total: 0 });
  const exercises = ref([]);

  // 从本地存储加载数据
  const loadWorkoutData = () => {
    try {
      const savedHistory = localStorage.getItem('workoutHistory');
      const savedStats = localStorage.getItem('workoutStats');
      const savedExercises = localStorage.getItem('exercises');

      if (savedHistory) workoutHistory.value = JSON.parse(savedHistory);
      if (savedStats) workoutStats.value = JSON.parse(savedStats);
      if (savedExercises) exercises.value = JSON.parse(savedExercises);
    } catch (error) {
      console.error('Failed to load workout data:', error);
    }
  };

  // 保存数据到本地存储
  const saveWorkoutData = () => {
    try {
      localStorage.setItem('workoutHistory', JSON.stringify(workoutHistory.value));
      localStorage.setItem('workoutStats', JSON.stringify(workoutStats.value));
      localStorage.setItem('exercises', JSON.stringify(exercises.value));
    } catch (error) {
      console.error('Failed to save workout data:', error);
    }
  };

  // 初始化
  loadWorkoutData();

  // 计算属性
  const completedWorkouts = computed(() => workoutHistory.value.filter(workout => workout.completed).length);
  const recentWorkouts = computed(() => [...workoutHistory.value].reverse().slice(0, 5));

  // 动作
  const setCurrentWorkout = (workout) => {
    currentWorkout.value = workout;
  };

  const addExerciseToCurrentWorkout = (exercise) => {
    if (!currentWorkout.value) return;
    if (!currentWorkout.value.exercises) {
      currentWorkout.value.exercises = [];
    }
    currentWorkout.value.exercises.push(exercise);
    saveWorkoutData();
  };

  const completeWorkout = (workoutId) => {
    const workout = workoutHistory.value.find(w => w.id === workoutId);
    if (workout) {
      workout.completed = true;
      workout.completedAt = new Date().toISOString();

      // 更新统计数据
      workoutStats.value.weekly += 1;
      workoutStats.value.monthly += 1;
      workoutStats.value.total += 1;

      saveWorkoutData();
    }
  };

  const addWorkoutToHistory = (workout) => {
    workoutHistory.value.push({
      id: Date.now(),
      ...workout,
      completed: false,
      createdAt: new Date().toISOString()
    });
    saveWorkoutData();
  };

  const fetchWorkoutStats = () => {
    // 在实际应用中，这里可能会从服务器获取数据
    return workoutStats.value;
  };

  const deleteWorkout = (workoutId) => {
    workoutHistory.value = workoutHistory.value.filter(w => w.id !== workoutId);
    saveWorkoutData();
  };

  return {
    currentWorkout,
    workoutHistory,
    workoutStats,
    exercises,
    completedWorkouts,
    recentWorkouts,
    setCurrentWorkout,
    addExerciseToCurrentWorkout,
    completeWorkout,
    addWorkoutToHistory,
    fetchWorkoutStats,
    deleteWorkout,
    saveWorkoutData
  };
});